
#include "web/pch.h"
#include "web/TcpServer.h"
#include "web/Thread.h"
#include "web/Buffer.h"
#include "web/wsa.h"

struct BufferTask : public Web::Thread
{
    std::shared_ptr<Web::TcpSocket> m_Socket;

    BufferTask(std::shared_ptr<Web::TcpSocket> sock) : m_Socket(sock)
    {
    }

    void Run()
    {
        while (1)
        {
            Web::Buffer buf;
            int len = m_Socket->Recv<Web::Buffer>(buf);

            printf("%s:%d Received Len %d: %d \n", m_Socket->GetIP(), m_Socket->GetPort(), len, buf.no);

            if (len <= 0)
            {

                printf("%s:%d [disconnnected ]\n",m_Socket->GetIP(), m_Socket->GetPort());
                break;
            }
        }
    }
};

int main()
{
    WSA::Init();
    
    auto tcpServer = std::make_shared<Web::TcpServer>(6666);

    std::vector<std::shared_ptr<Web::Thread>> m_Tasks;

    while (1)
    {
        auto newSock = tcpServer->Accept();
        std::cout << " IP: " << newSock->GetIP() << " Host: " << newSock->GetPort() << std::endl;
        auto newTask = std::make_shared<BufferTask>(newSock);
        newTask->Start();

        m_Tasks.push_back(newTask);
    }

    WSA::Clean();
    return 0;
}